package com.message.notify;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.message.notify.utils.HttpUtility;
import com.message.notify.utils.SharedPreferencesManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class NotificationReceiver extends BroadcastReceiver {
    String username = "";
    String password = "";
    @Override
    public void onReceive(Context context, Intent intent) {

//        notificationManager.notify(1, builder.build());
        String auth = intent.getStringExtra("token");
        username = intent.getStringExtra("username");
        password = intent.getStringExtra("password");

        Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //要执行的方法
                Log.d("TAG", "定时任务");
                getauth_warn(auth,null,context);
                getauth_examine(auth,null,context);

                //一分钟执行一次
                handler.postDelayed(this, 1*60*1000);
            }
        };

        handler.postDelayed(runnable, 1*60*1000);
    }

    public void getauth_warn(String auth,View view,Context context) {
        // 在此处创建并显示通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "1002")
                .setSmallIcon(R.drawable.app_icon)
                .setContentTitle("Your notification title")
                .setContentText("Your notification message")
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        // 对于Android O及更高版本，需要创建通知频道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = context.getString(R.string.app_name);
            String description = context.getString(R.string.app_name);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("1002", name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);

        }
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        //告警
        HttpUtility.get("http://106.37.212.101:8081/api/v1/alarm/alert/newest?span=1&showInfo=2&alertSignal=1", auth, new HttpUtility.OnRequestCallBack() {

            @Override
            public void onSuccess(String json) {
                Log.d("TAG", json);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    JSONObject data1 = jsonObject.getJSONObject("data");
                    notificationALarm(data1,1,builder,notificationManager,context);
//                    builder.setContentTitle("1000")
//                            .setContentText(data1.toString());
//                    notificationManager.notify(1, builder.build());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onError(String errorMsg) {
                Log.e("TAG", errorMsg);
            }

        });

        HttpUtility.get("http://106.37.212.101:8081/api/v1/alarm/alert/newest?span=1&showInfo=2&alertSignal=0", auth, new HttpUtility.OnRequestCallBack() {

            @Override
            public void onSuccess(String json) {
                Log.d("TAG", json);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    JSONObject data1 = jsonObject.getJSONObject("data");
                    notificationALarm(data1,0,builder,notificationManager,context);
//                    builder.setContentTitle("1000")
//                            .setContentText(data1.toString());
//                    notificationManager.notify(1, builder.build());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onError(String errorMsg) {
                Log.e("TAG", errorMsg);
            }

        });
//        builder.setContentTitle("1000")
//                            .setContentText("data1.toString()");
//                    notificationManager.notify(1, builder.build());
    }

    @SuppressLint("WrongConstant")
    public void notificationALarm(JSONObject data1,int type,NotificationCompat.Builder builder,NotificationManagerCompat notificationManager,Context context ) throws JSONException {

        JSONArray data;
        StringBuffer sb = new StringBuffer();

        String title = null;
        String SummaryText = null;
        Intent intent = new Intent(context, MainActivity.class);

        if(type == 0){//告警-恢复
            if("0".equals(data1.getString("total"))){
                return;
            }
            data = data1.getJSONArray("list");
            //sb.append("您有" + data1.get("total") + "条告警，请查收\n");
            SummaryText = "您有" + data1.get("total") + "条告警，请查收\n";
            intent.putExtra("notify","warn");
            title = "告警通知-恢复";
            for(int i = 0;i<data.length();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                sb.append("系统：" + jsonObject.get("sysName") + "\n");
                sb.append("站点：" +  jsonObject.get("stationName") + "\n");
                sb.append("告警内容：" + jsonObject.get("alertInfo") + "\n");
                sb.append("异常时间：" + jsonObject.get("alertTime")  + "\n");
                sb.append("------------------------------------\n");
            }
        }else if(type == 1){//告警-异常
            if("0".equals(data1.getString("total"))){
                return;
            }
            data = data1.getJSONArray("list");
            //sb.append("您有" + data1.get("total") + "条告警，请查收\n");
            SummaryText = "您有" + data1.get("total") + "条告警，请查收\n";
            intent.putExtra("notify","warn");
            title = "告警通知-异常";
            for(int i = 0;i<data.length();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                sb.append("系统：" + jsonObject.get("sysName") + "\n");
                sb.append("站点：" +  jsonObject.get("stationName") + "\n");
                sb.append("告警内容：" + jsonObject.get("alertInfo") + "\n");
                sb.append("异常时间：" + jsonObject.get("alertTime")  + "\n");
                sb.append("------------------------------------\n");
            }
        }else if(type == 2){//审批
            if("0".equals(data1.getString("totalCount"))){
                return;
            }
            data = data1.getJSONArray("data");
            //sb.append("您有" + data1.get("totalCount") + "条审批，请查收\n");
            SummaryText = "您有" + data1.get("totalCount") + "条审批，请查收\n";
            intent.putExtra("notify","examine");
            title = "审批通知";
            for(int i = 0;i<data.length();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                sb.append("审批：" + jsonObject.get("alarmContent") + "\n");
                sb.append("时间：" +  jsonObject.get("createTime") + "\n");
                sb.append("------------------------------------\n");
            }
        }
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.setBigContentTitle(title)
                .setSummaryText(SummaryText)
                .bigText(sb.toString());

        builder.setContentTitle(title)//设置消息通知标题
                .setContentText(sb.toString())//设置消息通知内容
                .setStyle(bigTextStyle)
                .setWhen(System.currentTimeMillis())//设置消息通知发送时间
                .setSmallIcon(R.mipmap.app_icon)//设置小童通知状态栏图标
                .setCategory(NotificationCompat.CATEGORY_MESSAGE) // 通知类别，"勿扰模式"时系统会决定要不要显示你的通知
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) // 屏幕可见性，锁屏时，显示icon和标题，内容隐藏
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);//设置消息优先级
        intent.putExtra("username",username);
        intent.putExtra("password",password);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setFullScreenIntent(pendingIntent, true);
        builder.setContentIntent(pendingIntent);
        notificationManager.notify(type, builder.build());

    }

    public void getauth_examine(String auth ,View view,Context context) {
        // 在此处创建并显示通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "1001")
                .setSmallIcon(R.drawable.app_icon)
                .setContentTitle("Your notification title")
                .setContentText("Your notification message")
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        // 对于Android O及更高版本，需要创建通知频道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = context.getString(R.string.app_name);
            String description = context.getString(R.string.app_name);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("1001", name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        //审批
        HttpUtility.get("http://124.17.81.85:8081/api/v1/alarm/apply/pending",auth, new HttpUtility.OnRequestCallBack() {

            @Override
            public void onSuccess(String json) {
                Log.d("TAG", json);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    JSONObject data1 = jsonObject.getJSONObject("data");
                    notificationALarm(data1,2,builder,notificationManager,context);


                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onError(String errorMsg) {
                Log.e("TAG", errorMsg);
            }

        });

    }

}